<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="文件名称" prop="fileName">
        <el-input
          v-model="queryParams.fileName"
          placeholder="请输入文件名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="文件大小" prop="fileSize">
        <el-input
          v-model="queryParams.fileSize"
          placeholder="请输入文件大小"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="上传时间" prop="uploadTime">
        <el-date-picker
          clearable
          v-model="queryParams.uploadTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择上传时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:transfer:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:transfer:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:transfer:remove']"
          >删除</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:transfer:export']"
          >导出</el-button
        >
      </el-col> -->
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="transferList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="文件唯一标识" align="center" prop="fileId" /> -->
      <el-table-column label="文件名称" align="center" prop="fileName" />
      <!-- <el-table-column label="文件大小" align="center" prop="fileSize" /> -->
      <el-table-column
        label="上传时间"
        align="center"
        prop="uploadTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.uploadTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="上传用户ID" align="center" prop="uploadUserId" /> -->
      <!-- <el-table-column label="下载次数" align="center" prop="downloadCount" /> -->
      <!-- <el-table-column label="文件存储路径" align="center" prop="filePath" >
        <template slot-scope="scope">
          <el-button type="" @click="">下载</el-button>
        </template>
        </el-table-column> -->
      <el-table-column label="文件(传输)状态" align="center" prop="fileStatus">
        <template slot-scope="scope">
          <span>{{ scope.row.fileStatus == 1 ? '未上传完成' : '完成' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="文件是否归档" align="center" prop="fileState">
        <template slot-scope="scope">
          <span>{{ scope.row.fileState == 1 ? '是' : '否' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="版本号" align="center" prop="infoExtend1" />
      <!-- <el-table-column label="扩展字段" align="center" prop="infoExtend2" /> -->
      <!-- <el-table-column label="扩展字段" align="center" prop="infoExtend3" /> -->
      <!-- <el-table-column label="扩展字段" align="center" prop="infoExtend4" /> -->
      <el-table-column
        label="创建时间"
        align="center"
        prop="createDate"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="更新时间"
        align="center"
        prop="updateDate"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="回收站状态" align="center" prop="recycleStatus" /> -->
      <el-table-column label="审批状态" align="center" prop="infoExtend3">
        <template slot-scope="scope">
          <el-tag>{{
            scope.row.infoExtend3 === 1
              ? '待审批'
              : scope.row.infoExtend3 === 2
              ? '审批中'
              : scope.row.infoExtend3 === 3
              ? '已通过'
              : scope.row.infoExtend3 === 4
              ? '已驳回'
              : ''
          }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:transfer:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:transfer:remove']"
            >删除</el-button
          >
          <el-button size="mini" type="text" @click="openPreview1(scope.row)"
            >下载</el-button
          >
          <el-button size="mini" type="text" @click="openPreview(scope.row)"
            >预览</el-button
          >
          <el-button
            size="mini"
            type="text"
            @click="handlePersonalPermission(scope.row)"
            >个人权限分配</el-button
          >
          <el-button
            size="mini"
            type="text"
            @click="handleDepartmentPermission(scope.row)"
            >部门权限分配</el-button
          >
          <el-button size="mini" type="text" @click="openDialog(scope.row)"
            >历史版本</el-button
          >
          <el-button
            size="mini"
            type="text"
            @click="handleLeaveMessage(scope.row)"
            >留言</el-button
          >
          <el-button
            size="mini"
            type="text"
            v-if="scope.row.infoExtend3 == 1"
            @click="handleViewHistoryMessages(scope.row)"
            >历史留言</el-button
          >
          <el-button
            size="mini"
            type="text"
            v-if="scope.row.infoExtend3 == 1"
            @click="add1(scope.row.fileId)"
            >发起审批</el-button
          >
          <el-button
            @click="record(scope.row)"
            size="mini"
            type="text"
            v-if="scope.row.infoExtend3 != 1"
            >审批记录</el-button
          >
          <el-button
            size="mini"
            type="text"
            v-if="
              scope.row.infoExtend3 / 1 == 3 && scope.row.fileState / 1 == 0
            "
            @click="handleUpdate1(scope.row)"
            >归档</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改文件传输对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="文件名称" prop="fileName">
          <el-input v-model="form.fileName" placeholder="请输入文件名称" />
        </el-form-item>
        <!-- <el-form-item label="文件大小" prop="fileSize">
          <el-input
            disabled
            v-model="form.fileSize"
            placeholder="请输入文件大小"
          />
        </el-form-item> -->
        <el-form-item label="上传时间" prop="uploadTime">
          <el-date-picker
            clearable
            v-model="form.uploadTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择上传时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="文件存储路径" label-width="110px" prop="filePath">
          <FileUpload
            v-if="open"
            ref="file"
            :limit="2"
            :fileSize="1000"
            v-model="form.filePath"
            :fileType="[]"
          />
        </el-form-item>
        <el-form-item label="版本号" prop="infoExtend1">
          <el-input-number
            v-model="form.infoExtend1"
            controls-position="right"
            :min="1"
          ></el-input-number>
        </el-form-item>
        <!-- <el-form-item label="扩展字段" prop="infoExtend1">
            <el-input v-model="form.infoExtend1" placeholder="请输入扩展字段" />
          </el-form-item>
          <el-form-item label="扩展字段" prop="infoExtend2">
            <el-input v-model="form.infoExtend2" placeholder="请输入扩展字段" />
          </el-form-item>
          <el-form-item label="扩展字段" prop="infoExtend3">
            <el-input v-model="form.infoExtend3" placeholder="请输入扩展字段" />
          </el-form-item>
          <el-form-item label="扩展字段" prop="infoExtend4">
            <el-input v-model="form.infoExtend4" placeholder="请输入扩展字段" />
          </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <leave-message ref="leaveMessage" @reset="getList" />
    <history-messages ref="historyMessages" />
    <file-preview-dialog ref="filePreviewDialog" />
    <file-preview-dialog1 ref="filePreviewDialog1" />
    <add-dialog1 ref="addDialog1" @dialogBack="getList" />
    <recordadd-or-update ref="RecordaddOrUpdate" />
    <history-version-dialog ref="historyDialog" />
    <personal-permission ref="personalPermission" />
  </div>
</template>

<script>
import {
  listTransfer,
  getTransfer,
  delTransfer,
  addTransfer,
  updateTransfer,
} from '@/api/file/transfer';
import leaveMessage from './components/leaveMessage.vue';
import historyMessages from './components/historyMessages.vue';
import filePreviewDialog from './components/filePreviewDialog.vue';
import filePreviewDialog1 from './components/filePreviewDialog1.vue';
import historyVersionDialog from './components/historyVersionDialog.vue';
import addDialog1 from '@/views/Appr/components/addDialog.vue'; //我是审批
import personalPermission from './components/personalPermission.vue';
import recordaddOrUpdate from '@/views/Appr/components/recordaddOrUpdate.vue';
import {
  approvalFromQueryApprovalByLaunch, // 获取业务有没有新增过
} from '@/api/system/Approval';
import { mapState } from 'vuex';

export default {
  name: 'Transfer',
  components: {
    leaveMessage,
    historyMessages,
    filePreviewDialog,
    filePreviewDialog1,
    addDialog1,
    personalPermission,
    historyVersionDialog,
    recordaddOrUpdate,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 文件传输表格数据
      transferList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        fileName: null,
        fileSize: null,
        uploadTime: null,
        uploadUserId: null,
        downloadCount: null,
        filePath: null,
        fileStatus: null,
        fileState: null,
        infoExtend1: null,
        infoExtend2: null,
        infoExtend3: null,
        infoExtend4: null,
        createDate: null,
        updateDate: null,
        recycleStatus: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        fileName: [
          { required: true, message: '文件名称不能为空', trigger: 'blur' },
        ],
        fileSize: [
          { required: true, message: '文件大小不能为空', trigger: 'blur' },
        ],
        uploadTime: [
          { required: true, message: '上传时间不能为空', trigger: 'blur' },
        ],
        uploadUserId: [
          { required: true, message: '上传用户ID不能为空', trigger: 'blur' },
        ],
        filePath: [
          { required: true, message: '文件存储路径不能为空', trigger: 'blur' },
        ],
        fileStatus: [
          { required: true, message: '文件状态不能为空', trigger: 'change' },
        ],
        fileState: [
          { required: true, message: '文件状态不能为空', trigger: 'blur' },
        ],
        recycleStatus: [
          { required: true, message: '回收站状态不能为空', trigger: 'change' },
        ],
        infoExtend1: [
          { required: true, message: '版本号不能为空', trigger: 'change' },
        ],
      },
    };
  },
  watch: {
    'form.filePath': {
      handler(newValue, oldValue) {
        // console.log('filePath changed from', oldValue, 'to', newValue);

        if (this.$refs && this.$refs.file && this.form.filePath) {
          console.log(
            'thisthisthisthisthisthisthisthisthis',
            this.$refs.file._data
          );

          const uploadList = this.$refs.file._data.uploadList;

          // 遍历 uploadList 中的每个文件
          let size = 0;
          uploadList.forEach((obj, index) => {
            size += obj.size;
          });
          this.form.fileSize = this.formatFileSize(size);
          console.log('FileUpload ref:', uploadList);
        }
      },
      deep: true, // 如果 form 是嵌套对象，需要 deep: true
    },
  },
  created() {
    this.getList();
  },
  computed: {
    ...mapState({
      user: (state) => state.user.user,
    }),
  },
  methods: {
    handleDepartmentPermission(row) {
      console.log(row);
    },
    handlePersonalPermission(row) {
      console.log(row);
      this.$refs.personalPermission.init(row);
    },
    openDialog(row) {
      this.$refs.historyDialog.init(row.fileId);
    },
    add1(id) {
      let type = '1';
      this.$refs.addDialog1.init('', '', id, type);
      // this.$refs.addDialog.handleAdd(id);
    },
    handleUpdate1(row) {
      this.reset();
      const recycleBinId = row.fileId;
      // 使用 async/await 来处理异步操作
      this.getBin(recycleBinId);
    },
    async getBin(recycleBinId) {
      try {
        const response = await getTransfer(recycleBinId); // 获取回收站数据
        this.form = response.data; // 将数据赋值给 form

        // 弹出确认框
        this.$modal
          .confirm('是否归档当前的文件')
          .then(async () => {
            this.form.fileState = '1'; // 修改状态
            await updateTransfer(this.form); // 更新回收站数据
            this.getList(); // 刷新列表
            this.$modal.msgSuccess('归档成功'); // 提示成功
          })
          .catch(() => {
            // 用户取消操作或发生错误时的处理
          });
      } catch (error) {
        // 处理 getBin 或 updateBin 的错误
        console.error('获取或是否归档当前的文件数据失败:', error);
        this.$modal.msgError('操作失败，请重试');
      }
    },
    async record(row) {
      const res1 = await approvalFromQueryApprovalByLaunch({
        pageIndex: 1,
        pageSize: 20,
        userId: this.user.userId,
        businessId: row.id,
      });
      const records = res1.data.records;
      if (records.length > 0) {
        this.$refs.RecordaddOrUpdate.init(records[0].id, records[0]);
      }
    },
    openPreview1(row) {
      this.$refs.filePreviewDialog1.init(parseFileList(row.filePath));
      // 处理函数
      function parseFileList(fileUrls) {
        // 按逗号分隔
        const urls = fileUrls.split(',');

        // 提取文件名和后缀
        const fileList = urls.map((url) => {
          // 获取文件名（从最后一个斜杠开始）
          const fileName = url.split('/').pop();
          // 获取文件后缀（从最后一个点开始）
          const fileExtension = fileName.split('.').pop();
          const nameWithoutExtension = fileName
            .split('.')
            .slice(0, -1)
            .join('.');
          const match = url.match(/[^/]+\.[^/]+$/);
          // 返回对象
          return {
            name: nameWithoutExtension,
            name1: match[0],
            type: fileExtension,
            url: url,
          };
        });

        return fileList;
      }
    },
    openPreview(row) {
      this.$refs.filePreviewDialog.init(parseFileList(row.filePath));
      // 处理函数
      function parseFileList(fileUrls) {
        // 按逗号分隔
        const urls = fileUrls.split(',');

        // 提取文件名和后缀
        const fileList = urls.map((url) => {
          // 获取文件名（从最后一个斜杠开始）
          const fileName = url.split('/').pop();
          // 获取文件后缀（从最后一个点开始）
          const fileExtension = fileName.split('.').pop();
          const nameWithoutExtension = fileName
            .split('.')
            .slice(0, -1)
            .join('.');
          // 返回对象
          return {
            name: nameWithoutExtension,
            type: fileExtension,
            url: url,
          };
        });

        return fileList;
      }
    },
    handleLeaveMessage(row) {
      this.$refs.leaveMessage.showLeaveMessageDialog(row.fileId);
    },
    handleViewHistoryMessages(row) {
      this.$refs.historyMessages.showLeaveMessageDialog(row.fileId);
    },
    formatFileSize(bytes) {
      if (bytes === 0) return '0 Bytes';

      const k = 1024;
      const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];

      const i = Math.floor(Math.log(bytes) / Math.log(k));
      const sizeInUnit = parseFloat((bytes / Math.pow(k, i)).toFixed(2));

      return `${sizeInUnit} ${sizes[i]}`;
    },
    /** 查询文件传输列表 */
    getList() {
      this.loading = true;
      listTransfer(this.queryParams).then((response) => {
        this.transferList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        fileId: null,
        fileName: null,
        fileSize: null,
        uploadTime: null,
        uploadUserId: null,
        downloadCount: null,
        filePath: null,
        fileStatus: null,
        fileState: null,
        infoExtend1: null,
        infoExtend2: null,
        infoExtend3: null,
        infoExtend4: null,
        createBy: null,
        createDate: null,
        updateBy: null,
        updateDate: null,
        recycleStatus: null,
      };
      this.resetForm('form');
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm');
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.fileId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    async handleAdd() {
      this.reset();
      this.open = true;
      await this.$nextTick();
      this.form.infoExtend1 = 1;
      this.title = '添加文件传输';
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const fileId = row.fileId || this.ids;
      getTransfer(fileId).then(async (response) => {
        this.form = response.data;
        this.open = true;
        await this.$nextTick();
        this.title = '修改文件传输';
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          console.log();
          // this.$refs.file.uploadTasks
          let arr = this.$refs.file.uploadTasks;
          if (this.form.fileId != null) {
            const allProgressIs100 = arr.every((e) => e.obj.progress === 100);
            if (!allProgressIs100) {
              arr.forEach((e) => {
                e.isPaused = true;
              });
              this.form.fileStatus = 1;
            } else {
              this.form.fileStatus = 0;
            }
            updateTransfer(this.form).then((response) => {
              this.$modal.msgSuccess('修改成功');
              this.open = false;
              this.getList();
            });
          } else {
            this.form.fileState = 0;
            // this.form.fileStatus = 0;
            const allProgressIs100 = arr.every((e) => e.obj.progress === 100);
            if (!allProgressIs100) {
              arr.forEach((e) => {
                e.isPaused = true;
              });
              this.form.fileStatus = 1;
            } else {
              this.form.fileStatus = 0;
            }
            addTransfer(this.form).then((response) => {
              this.$modal.msgSuccess('新增成功');
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const fileIds = row.fileId || this.ids;
      this.$modal
        .confirm('是否确认删除文件')
        .then(function () {
          return delTransfer(fileIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess('删除成功');
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'system/transfer/export',
        {
          ...this.queryParams,
        },
        `transfer_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
